<template>
    <div class="content">
        <el-row>
            <el-col :span="24">
                <div class="table-head">
                    <el-button type="primary" @click="uploadFlag = true">新增</el-button>
                    <el-dialog v-model="uploadFlag" title="请上传图片" width="400">
                        <div class="upload-content">
                            <el-upload ref="uploadRef" :action="uploadUrl" list-type="picture-card" :auto-upload="false"
                                :limit="1" :on-error="handleError" :on-success="handleSuccess"
                                :before-upload="beforeAvatarUpload"></el-upload>
                            <el-button type="success" @click="submitUpload">保存</el-button>
                        </div>

                    </el-dialog>
                </div>
            </el-col>
        </el-row>
        <el-table ref="multipleTableRef" :data="list" row-key="id" style="width: 100%">
            <el-table-column label="id" prop="id" />
            <el-table-column label="上传时间" width="240">
                <template #default="scope">{{ scope.row.createTime }}</template>
            </el-table-column>
            <el-table-column label="图片" width="240">
                <template #default="scope">
                    <el-image style="width: auto; height: 100px" :src="imgUrl + scope.row.url" :zoom-rate="1.2"
                        :max-scale="7" :min-scale="0.2" :preview-src-list="[imgUrl + scope.row.url]" show-progress
                        fit="cover" preview-teleported />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" round @click="lookRrcode(scope.row.url)">查看二维码</el-button>
                    <el-button type="info" round @click="delEvt(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
            id
        </el-table>
        <el-pagination :total="pageData.total" :page-size="10" layout="prev, pager, next,total"
            @current-change="handleCurrentChange" background />
        <el-dialog v-model="flag" title="二维码详情" width="400">
            <div class="dialog-content">
                <qrcode-vue :value="qrCodeData" :size="200" level="H" />
            </div>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue'
import QrcodeVue from 'qrcode.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getList, deleteById } from '@/api/qrcode'


// 列表数据和分页
const pageData = ref({
    current: 1,
    size: 10,
    total: 0
})

const flag = ref<boolean>(false)  //弹窗控制器
const uploadFlag = ref<boolean>(false)  //上传弹窗控制器
const uploadRef = ref<any>(null)  // 上传组件ref
const list = ref([])  // 存放真实的数据列表

const qrCodeData = ref('')  // 用于存放二维码数据


const uploadUrl = import.meta.env.VITE_BASE_URL + '/api/sys_file/upload'   // 上传地址

const imgUrl = 'http://www.eff.org.cn:2000/sys_file/show/'   // 真实的地址前缀
const previewImaUrl = import.meta.env.VITE_BASE_URL + '/previewImage?id=' //预览图片时的地址






// 获取页面数据
const getPageData = () => {
    const params = {
        size: pageData.value.size,
        current: pageData.value.current
    }
    // 这里可以调用接口获取数据
    getList(params).then((res) => {
        if (res.code === 0) {
            list.value = res.data.records
            pageData.value.total = res.data.total
        } else {
            ElMessage.error(res.message)
        }
    })
}

// 查看二维码
const lookRrcode = (e: string | null) => {
    qrCodeData.value = previewImaUrl + e
    flag.value = !flag.value
}
// 删除数据
const delEvt = async (e) => {
    try {
        await ElMessageBox.confirm(
            '代理将永久删除该文件。继续吗？',
            '警告',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        // 用户点击了"确定"，执行删除操作
        const res = await deleteById(e)

        if (res.code === 0) {
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            getPageData()
        } else {
            ElMessage.error(res.message)
        }
    } catch (error) {
        // 用户点击"取消"或关闭对话框
        if (error === 'cancel' || error === 'close') {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        } else {
            // 其他错误
            console.error('删除失败:', error)
            ElMessage.error('删除失败，请重试')
        }
    }
}
// 提交上传
const submitUpload = () => {
    uploadRef.value!.submit()
}
// 上传成功回调
const handleSuccess = (response, file, fileList) => {
    ElMessage({
        message: '上传成功',
        type: 'success'
    })
    uploadFlag.value = false
    getPageData()

}
// 上传失败回调
const handleError = (err, file, fileList) => {
    console.log('err=', err);
    ElMessage.error('上传失败');
}
// 上传前的验证
const beforeAvatarUpload = (file) => {
    // 常见的图片类型验证
    const isImage = file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif' ||
        file.type === 'image/webp' ||
        file.type === 'image/svg+xml';

    if (!isImage) {
        ElMessage.error('请上传图片格式文件!');
        return false;
    }

    // 文件大小验证（可选）
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 5MB!');
        return false;
    }

    return true;
}
// 分页变化
const handleCurrentChange = (page: number) => {
    console.log('当前页码：', page);
    pageData.value.current = page
    getPageData()
}
getPageData()

</script>

<style scoped lang="scss">
.content {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .table-head {
        display: flex;
    }

    .dialog-content {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .upload-content {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
    }
}
</style>